package com.example.springmvc.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * @Description:
 * @Author: lijiewei
 * @Date: 2020/7/21$ 21:45$
 */
@Component
@WebFilter(urlPatterns="/**", filterName = "requestAttrFilter")
public class RequestAttrFilter implements Filter {

    //排除不拦截的url
    private static final String[] EXCLUDE_PATH_PATTERNS = { "/user/get1", "/dept/get1"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Enumeration e   =   req.getHeaderNames();
        while   (e.hasMoreElements())   {
            String   name   =   (String)e.nextElement();
            String   value   =   req.getHeader(name);
            System.out.println(name   +   "   =   "   +   value);
        }
        StringBuffer requestURL = req.getRequestURL();
        String uri = req.getRequestURI();
        //对一些url不拦截
        if (Arrays.asList(EXCLUDE_PATH_PATTERNS).contains(uri)) {
            chain.doFilter(request, response);
        }
        request.setAttribute("data", "request中放的数据");
        if (true) {
            //满足要求放行
            chain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
